package com.aynu.gulimall.cart.serivce.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.aynu.common.constant.CartConstant;
import com.aynu.common.utils.R;
import com.aynu.gulimall.cart.feign.ProductFeignService;
import com.aynu.gulimall.cart.interceptor.CartInterceptor;
import com.aynu.gulimall.cart.serivce.CartService;
import com.aynu.gulimall.cart.to.UserInfoTo;
import com.aynu.gulimall.cart.vo.CartItemVo;
import com.aynu.gulimall.cart.vo.CartVo;
import com.aynu.gulimall.cart.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author mj
 * @version 1.0
 * @date 2021/3/20 18:29
 */
@Service
@Slf4j
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    //redis存储的前缀
    private final String CART_PREFIX = "gulimall:cart:";

    @Override
    public CartItemVo addToCart(Long skuId, Integer num) {
        //1、获取购物车
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String productRedisValue = (String) cartOps.get(skuId.toString());
        //如果没有就添加数据
        if (StringUtils.isEmpty(productRedisValue)) {

            //2、添加新的商品到购物车(redis)
            CartItemVo cartItemVo = new CartItemVo();
            //开启第一个异步任务
            CompletableFuture<Void> getSkuInfoFuture = CompletableFuture.runAsync(() -> {
                //1、远程查询当前要添加商品的信息
                R productSkuInfo = productFeignService.info(skuId);
                SkuInfoVo skuInfo = productSkuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                //数据赋值操作
                cartItemVo.setSkuId(skuInfo.getSkuId());
                cartItemVo.setTitle(skuInfo.getSkuTitle());
                cartItemVo.setImage(skuInfo.getSkuDefaultImg());
                cartItemVo.setPrice(skuInfo.getPrice());
                cartItemVo.setCount(num);
            }, threadPoolExecutor);

            //开启第二个异步任务
            CompletableFuture<Void> getSkuAttrValuesFuture = CompletableFuture.runAsync(() -> {
                //2、远程查询skuAttrValues组合信息
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItemVo.setSkuAttrValues(skuSaleAttrValues);
            }, threadPoolExecutor);

            //等待所有的异步任务全部完成
            try {
                CompletableFuture.allOf(getSkuInfoFuture, getSkuAttrValuesFuture).get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }

            String cartItemJson = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(), cartItemJson);

            return cartItemVo;
        } else {
            //购物车有此商品，只需修改数量
            CartItemVo cartItemVo = JSON.parseObject(productRedisValue, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount() + num);
            //修改redis的数据
            String cartItemJson = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(), cartItemJson);

            return cartItemVo;
        }
    }

    @Override
    public CartItemVo getCartBySkuId(Long skuId) {
        //获取购物车
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String str = (String) cartOps.get(skuId.toString());
        if (str != null) {
            return JSON.parseObject(str, CartItemVo.class);
        }
        return null;
    }

    @Override
    public CartVo getCart() {
        CartVo cartVo = new CartVo();
        //先得到当前用户信息
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        if (userInfoTo.getUserId() != null) {
            //1、登陆
            //获取登陆的购物车的key
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            //获取临时购物车的key
            String userKey = CART_PREFIX + userInfoTo.getUserKey();
            //2、获取临时购物中的数据
            List<CartItemVo> tempCartItem = getCartItemVo(userKey);
            if (tempCartItem != null) {
                //临时购物车中有数据，需要合并到登陆的购物车中
                for (CartItemVo cartItemVo : tempCartItem) {
                    //合并购物车
                    addToCart(cartItemVo.getSkuId(), cartItemVo.getCount());
                }
                //清空购物车
                clearCart(userKey);
            }
            //3、查询登陆后的购物车的数据【包括临时购物车+登陆后购物车】
            List<CartItemVo> cartItemVos = getCartItemVo(cartKey);
            cartVo.setItems(cartItemVos);

            return cartVo;
        } else {
            //没登陆
            String userKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItemVo> cartItemVos = getCartItemVo(userKey);
            cartVo.setItems(cartItemVos);
            return cartVo;
        }
    }

    /**
     * 获取到我们要操作的购物车
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        //先得到当前用户信息
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();

        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            //gulimall:cart:1
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }

        //绑定指定的key操作Redis
        return redisTemplate.boundHashOps(cartKey);
    }

    private List<CartItemVo> getCartItemVo(String cartKey) {
        //绑定购物车key
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        //获取所有的购物车数据
        List<Object> values = hashOps.values();
        if (!CollectionUtils.isEmpty(values)) {
            List<CartItemVo> itemVos = values.stream().map((item) -> {
                if (item != null) {
                    String str = (String) item;
                    return JSON.parseObject(str, CartItemVo.class);
                } else {
                    log.error("购物车的购物项为空");
                    return null;
                }
            }).collect(Collectors.toList());
            return itemVos;
        }
        return null;
    }

    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //修改选中状态
        CartItemVo cartItemVo = getCartBySkuId(skuId);
        cartItemVo.setCheck(check.equals(1));
        String itemStr = JSON.toJSONString(cartItemVo);
        //重新放入redis中
        cartOps.put(skuId.toString(), itemStr);
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        CartItemVo cartItemVo = getCartBySkuId(skuId);
        cartItemVo.setCount(num);

        //如果数量为0，则删除该商品
        if (num == 0) {
            BoundHashOperations<String, Object, Object> cartOps = getCartOps();
            cartOps.delete(skuId.toString());
        } else {
            BoundHashOperations<String, Object, Object> cartOps = getCartOps();
            String itemVo = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(), itemVo);
        }

    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    public List<CartItemVo> blockHandler(BlockException e) {
        log.error("currentUserCartItems被降级了");
        return new ArrayList<>();
    }

    /**
     * fallbackClass =
     *
     * @return
     */
    @SentinelResource(value = "currentUserCartItems", blockHandler = "blockHandler")
    @Override
    public List<CartItemVo> currentUserCartItems() {

        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        try (Entry entry = SphU.entry("currentUserCartItems")) {
            if (userInfoTo == null) {
                return null;
            } else {
                List<CartItemVo> cartItemVo = getCartItemVo(CART_PREFIX + userInfoTo.getUserId());
                if (cartItemVo != null) {
                    //获取所有被选中的购物项
                    List<CartItemVo> collect = cartItemVo.stream().filter(CartItemVo::getCheck).map(item -> {
                        log.info("远程调用商品服务，查询最新的阿价格");
                        BigDecimal price = productFeignService.getPrice(item.getSkuId());
                        item.setPrice(price);
                        return item;
                    }).collect(Collectors.toList());
                    return collect;
                } else {
                    return null;
                }
            }
        } catch (BlockException e) {
            log.error("自定义降级资源保护触发");
            return null;
        }
    }
}
